<template>
  <!-- 首页 -->
  <div class="dashboard-container">
    <!-- 加载中 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else class="dashboard">
      <div class="dashboard-header">
        <h1>控制台</h1>
        <p>欢迎来到后台管理系统</p>
      </div>
      
      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :span="8" :xs="24" :sm="12" :md="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon user-icon">
                <el-icon :size="24"><Box /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ dashboardData.totalDevices || apiData?.zhuztbt?.match(/(\d+)台/) && apiData.zhuztbt.match(/(\d+)台/)[1] || '0' }}</div>
                <div class="stat-title">总设备数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8" :xs="24" :sm="12" :md="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon visit-icon">
                <el-icon :size="24"><Checked /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ apiData?.zhuztzzbt?.match(/(\d+)台/) && apiData.zhuztzzbt.match(/(\d+)台/)[1] || '0' }}</div>
                <div class="stat-title">在租设备</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8" :xs="24" :sm="12" :md="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon order-icon">
                <el-icon :size="24"><Timer /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ apiData?.zhuztdzbt?.match(/(\d+)台/) && apiData.zhuztdzbt.match(/(\d+)台/)[1] || '0' }}</div>
                <div class="stat-title">待租设备</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
       <!-- 设备图表 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="24">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>设备状态分布 ({{ apiData?.zhuztbt || '总设备数: 638台' }}, {{ apiData?.zulincppxb || '待租用: 49台' }}, {{ apiData?.zhuztdzbt || '在租设备: 587台' }})</span>
              </div>
            </template>
            <div class="echarts-container" v-if="!loading">
              <div class="responsive-echart" ref="deviceChartRef"></div>
            </div>
            <el-empty v-else description="图表加载中..." />
          </el-card>
        </el-col>
      </el-row>

      <!-- 统计表格 -->
      <el-row :gutter="20" class="stats-table-row" v-if="getStatsData().length > 0">
        <el-col :span="24">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>统计报表</span>
              </div>
            </template>
            <div class="stats-buttons">
              <el-button
                v-for="(stat, index) in getStatsData()"
                :key="index"
                :type="getButtonType(index)"
                @click="navigateToUrl(stat.url, stat.bt)"
                class="stat-button"
              >
                {{ stat.bt }}
                <el-badge v-if="stat.shuliang > 0" :value="stat.shuliang" class="stats-badge" />
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { 
  User, 
  Document, 
  DataBoard, 
  Box, 
  Checked, 
  Timer,
  UserFilled,
  Edit,
  DocumentDelete,
  Postcard,
  DocumentChecked,
  OfficeBuilding,
  Setting,
  Monitor,
  Files,
  Management,
  Position,
  ShoppingCartFull
} from '@element-plus/icons-vue'
import * as echarts from 'echarts/core'
import { BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  LegendComponent
} from 'echarts/components'
import { LabelLayout } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import request, { getApiPath } from '@/utils/request'
import { Base64 } from 'js-base64'

// 注册必需的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  LegendComponent,
  BarChart,
  LabelLayout,
  CanvasRenderer
])

export default {
  name: 'Dashboard',
  components: {
    User,
    Document,
    DataBoard,
    Box,
    Checked,
    Timer,
    UserFilled,
    Edit,
    DocumentDelete,
    Postcard,
    DocumentChecked,
    OfficeBuilding,
    Setting,
    Monitor,
    Files,
    Management,
    Position,
    ShoppingCartFull
  },
  setup() {
    const router = useRouter()
    const loading = ref(true)
    const dashboardData = reactive({
      userCount: 0,
      visitCount: 0,
      orderCount: 0,
      revenue: 0
    })
    
    const deviceChartRef = ref(null)
    let deviceChart = null
    const apiData = ref(null)
    
    // 获取工作提醒数据
    const getWorkReminderData = () => {
      if (!apiData.value?.caidan) return []
      const workReminder = apiData.value.caidan.find(item => item.flbt === '工作提醒')
      return workReminder ? workReminder.shuzu : []
    }
    
    // 获取统计报表数据
    const getStatsData = () => {
      if (!apiData.value?.caidan) return []
      const stats = apiData.value.caidan.find(item => item.flbt === '统计报表')
      return stats ? stats.shuzu : []
    }
    
    // 获取按钮类型（循环使用不同颜色）
    const getButtonType = (index) => {
      const types = ['primary', 'success', 'warning', 'danger', 'info']
      return types[index % types.length]
    }
    
    // 解析URL参数
    const parseUrlParams = (url) => {
      try {
        if (!url) return null
        
        // 从URL中提取查询参数
        const urlObj = new URL(url, 'http://localhost')
        const csParam = urlObj.searchParams.get('cs')
        
        if (csParam) {
          // URL解码
          const decodedParam = decodeURIComponent(csParam)
          console.log('解码后的参数:', decodedParam)
          
          // 解析JSON
          const parsedParam = JSON.parse(decodedParam)
          console.log('解析后的参数对象:', parsedParam)
          
          return parsedParam
        }
        
        return null
      } catch (error) {
        console.log('解析URL参数失败:', error)
        return null
      }
    }
    
    // 跳转到指定URL（uniapp风格的参数传递）
    const navigateToUrl = (url, itemTitle = '') => {
      if (!url && !itemTitle) return
      
      console.log('=== uniapp风格控制台跳转 ===')
      console.log('点击的URL:', url, '标题:', itemTitle)
      
      // 解析URL中的cs参数，获取原始参数
      let originalParams = null
      if (url) {
        originalParams = parseUrlParams(url)
        console.log('解析出的原始参数:', originalParams)
      }
      
      // 如果没有原始参数，创建默认参数
      if (!originalParams) {
        originalParams = {
          number: 1,
          cxlx: 101, // 默认查询类型
          key: '',
          faid: 560602715 // 默认faid  
        }
        console.log('创建默认参数:', originalParams)
      }
      
      // 构建uniapp风格的跳转参数
      const uniappParams = {
        faid: originalParams.faid || 560602715,
        cxlx: originalParams.cxlx || 101,
        liuchengbh: originalParams.liuchengbh || '',
        key: originalParams.key || '',
        number: originalParams.number || 1
      }
      
      console.log('uniapp风格参数:', uniappParams)
      
      // 直接跳转到业务列表页面，使用uniapp风格的路由和参数
      const businessUrl = '/business/hetonglclb/hetonglclb'
      
      console.log('跳转到业务页面:', businessUrl)
      console.log('传递参数:', uniappParams)
      
      // 使用router.push的query方式传递参数，就像uniapp那样
      router.push({
        path: businessUrl,
        query: uniappParams
      })
      
      console.log('=== uniapp风格跳转完成 ===')
    }
    
    // 获取控制台数据
    const fetchDashboardData = async () => {
      try {
        loading.value = true
        
        // 先获取动态菜单数据，里面包含了设备图表所需的数据
        await fetchApiData()
        
        // 模拟一些仪表盘数据
        dashboardData.userCount = 256
        dashboardData.visitCount = 128
        dashboardData.orderCount = 32
        dashboardData.revenue = 15800
      } catch (error) {
        console.log('获取控制台数据失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 获取API数据
    const fetchApiData = async () => {
      try {
        // 获取用户信息和openid
        const openid = localStorage.getItem('openid') || "17524180246839845722"
        
        const bs64_cs = {
          openid,
          banbenhao: '5.2.06121'
        }
        
        const cs = {
          ctype: 'zlxt_3_get_index',
          bs64_cs: Base64.encode(JSON.stringify(bs64_cs)),
          bs64_obj: '',
          bs64_list: '',
          ids: ''
        }
        
        const res = await request.post(getApiPath(cs.ctype), { canshu: cs })
        console.log('首页API数据 (zlxt_3_get_index):', res) // 首页使用zlxt_3_get_index接口
        
        if (res && (res.leixing === 'ok' || (res.data && res.data.leixing === 'ok'))) {
          apiData.value = res.leixing === 'ok' ? res : res.data

          // 保存首页API用户信息到 localStorage，供全局使用
          if (apiData.value.user_zsxm) {
            localStorage.setItem('user_zsxm', apiData.value.user_zsxm)
          }
          // 也可保存整个用户对象
          localStorage.setItem('userInfo', JSON.stringify({
            user_zsxm: apiData.value.user_zsxm || '',
            user_dlm: apiData.value.user_dlm || '',
            user_gw: apiData.value.user_gw || '',
            avatarurl: apiData.value.avatarurl || ''
          }))

          // 打印菜单数据结构用于调试
          console.log('菜单数据结构:', apiData.value.caidan)

          // 数据加载完成后初始化图表
          nextTick(() => {
            initDeviceChart()
          })
        }
      } catch (error) {
        console.log('获取API数据失败:', error)
      }
    }
    
    // 初始化设备图表
    const initDeviceChart = () => {
      console.log('=== 开始初始化图表 ===')
      console.log('deviceChartRef.value:', deviceChartRef.value)
      console.log('apiData.value:', apiData.value)
      console.log('apiData.value?.zulincppxb:', apiData.value?.zulincppxb)
      console.log('apiData.value?.dzshuzu:', apiData.value?.dzshuzu)
      console.log('apiData.value?.zzshuzu:', apiData.value?.zzshuzu)
      console.log('apiData.value?.liebt:', apiData.value?.liebt)
      
      if (!deviceChartRef.value) {
        console.log('图表容器DOM元素不存在')
        return
      }
      
      if (!apiData.value) {
        console.log('API数据不存在')
        return
      }
      
      // 放宽初始化条件，只要有API数据就尝试初始化
      console.log('准备初始化ECharts实例...')
      
      // 确保对应的DOM元素存在
      deviceChart = echarts.init(deviceChartRef.value)
      console.log('ECharts实例创建成功')
      
      // 将数据转换为图表所需格式，提供默认值
      const dzshuzu = apiData.value.dzshuzu ? apiData.value.dzshuzu.map(v => v === 0 ? null : v) : [10, 20, 15, 25, 30]
      const zzshuzu = apiData.value.zzshuzu ? apiData.value.zzshuzu.map(v => v === 0 ? null : v) : [50, 60, 45, 70, 80]
      const categories = apiData.value.liebt || ['类别1', '类别2', '类别3', '类别4', '类别5']
      
      console.log('处理后的数据:')
      console.log('dzshuzu:', dzshuzu)
      console.log('zzshuzu:', zzshuzu)
      console.log('categories:', categories)
      
      // 图表配置（适配PC和移动端，字体、间距、legend、tooltip等优化）
      const isMobile = window.innerWidth < 600
      const option = {
        title: {
          text: apiData.value.zhuztbt || '设备状态分布',
          left: 'center',
          textStyle: {
            fontSize: isMobile ? 14 : 16,
            fontWeight: 'normal'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: '#fff',
          borderColor: '#eee',
          borderWidth: 1,
          textStyle: {
            color: '#333',
            fontSize: isMobile ? 12 : 14
          },
          extraCssText: 'box-shadow:0 2px 8px rgba(0,0,0,0.08);',
          formatter: function(params) {
            let result = params[0].axisValue + '<br/>'
            params.forEach(item => {
              const value = item.value || 0
              result += `<span style="color:${item.color}">●</span> ${item.seriesName}: ${value}台<br/>`
            })
            return result
          }
        },
        legend: {
          data: [apiData.value.zhuztdzbt || '待租', apiData.value.zhuztzzbt || '在租'],
          bottom: isMobile ? 0 : '5%',
          left: 'center',
          itemGap: isMobile ? 8 : 20,
          textStyle: {
            fontSize: isMobile ? 12 : 14
          }
        },
        grid: {
          left: isMobile ? '6%' : '3%',
          right: isMobile ? '6%' : '4%',
          bottom: isMobile ? 40 : '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: categories,
          axisLabel: {
            rotate: isMobile ? 30 : 45,
            interval: 0,
            fontSize: isMobile ? 10 : 12,
            overflow: 'break',
            lineHeight: isMobile ? 14 : 16,
            formatter: function(value) {
              // 移动端自动换行
              if (isMobile && value.length > 4) {
                return value.slice(0, 4) + '\n' + value.slice(4)
              }
              return value
            }
          },
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} 台',
            fontSize: isMobile ? 10 : 12
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#f0f0f0'
            }
          }
        },
        series: [
          {
            name: apiData.value.zhuztdzbt || '待租',
            type: 'bar',
            // 不堆叠，左右并排
            barGap: 0,
            emphasis: {
              focus: 'series'
            },
            data: dzshuzu,
            barWidth: isMobile ? '40%' : '20%',
            itemStyle: {
              color: '#FF4444'
            },
            label: {
              show: true,
              position: 'top',
              fontSize: isMobile ? 10 : 12,
              color: '#333',
              formatter: function(params) {
                return params.value > 0 ? params.value : ''
              }
            }
          },
          {
            name: apiData.value.zhuztzzbt || '在租',
            type: 'bar',
            // 不堆叠，左右并排
            barGap: 0,
            emphasis: {
              focus: 'series'
            },
            data: zzshuzu,
            barWidth: isMobile ? '40%' : '20%',
            itemStyle: {
              color: '#67C23A'
            },
            label: {
              show: true,
              position: 'top',
              fontSize: isMobile ? 10 : 12,
              color: '#333',
              formatter: function(params) {
                return params.value > 0 ? params.value : ''
              }
            }
          }
        ],
        animationDuration: 1000,
        animationEasing: 'cubicOut'
      }
      
      console.log('图表配置:', option)
      
      // 设置配置项并渲染图表
      deviceChart.setOption(option)
      console.log('图表配置已设置，渲染完成')
      
      // 监听窗口大小变化，调整图表大小
      window.addEventListener('resize', () => {
        if (deviceChart) {
          deviceChart.resize()
          console.log('图表已重新调整大小')
        }
      })
      
      console.log('=== 图表初始化完成 ===')
    }
    
    onMounted(() => {
      fetchDashboardData()
      
      // 延迟执行图表初始化，确保DOM已经渲染
      setTimeout(() => {
        console.log('延迟初始化图表...')
        initDeviceChart()
      }, 1000)
    })
    
    return {
      loading,
      dashboardData,
      deviceChartRef,
      apiData,
      getWorkReminderData,
      getStatsData,
      getButtonType,
      navigateToUrl
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.loading-container {
  padding: 20px;
}

.dashboard-header {
  margin-bottom: 20px;
}

.dashboard-header h1 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
}

.dashboard-header p {
  color: #909399;
  font-size: 14px;
}

.stats-row,
.chart-row,
.work-process-row,
.stats-table-row,
.business-systems-row {
  margin-bottom: 20px;
}

/* 响应式ECharts容器 */
.echarts-container {
  width: 100%;
  min-height: 220px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.responsive-echart {
  width: 100%;
  height: 400px;
  max-width: 100vw;
}
@media (max-width: 600px) {
  .dashboard-container {
    padding: 4px;
  }
  .responsive-echart {
    height: 220px;
    min-height: 180px;
  }
}

/* ...保留原有其它样式... */
</style>
